from stw_app import models
from stw_app.models import UserInfo
from django.shortcuts import render, redirect
from django.http import JsonResponse, HttpResponse
from django.views.decorators.csrf import csrf_exempt


@csrf_exempt
def get_comments(request):
    if request.method == "POST":
        worker_id = request.POST.get('worker_id')
        worker_id = int(worker_id)
        comments = models.Judgement.objects.filter(judged_id=worker_id).order_by('-release_time')[:5]
        data = []
        for comment in comments:
            item = {
                'releaser_id': comment.releaser_id,
                'order_id': comment.order_id,
                'comment_info': comment.judgement_info,
                'release_time': comment.release_time,
                'score': comment.score,
                'belief_score': comment.belief_score,
            }
            data.append(item)
        return JsonResponse({'success': True, 'data': data})
    return JsonResponse({'success': False})

@csrf_exempt
def get_releasers(request):
    if request.method == "POST":
        releasers_id = request.POST.get('releasers_id')
        releasers_list = releasers_id.split(',')
        releasers = []
        for index in range(5):
            releaser_id = int(releasers_list[index])
            releaser = models.UserInfo.objects.get(id=releaser_id)
            releasers.append(releaser.nick_name)
        return JsonResponse({'success': True, 'data': releasers})
    return JsonResponse({'success': False})

@csrf_exempt
def get_orders(request):
    if request.method == "POST":
        orders_id = request.POST.get('orders_id')
        orders_list = orders_id.split(',')
        print(orders_list)
        orders = []
        for index in range(5):
            order_id = int(orders_list[index])
            order = models.Order.objects.get(id=order_id)
            print(order.title)
            orders.append(order.title)
        return JsonResponse({'success': True, 'data': orders})
    return JsonResponse({'success': False})

@csrf_exempt
def report(request):
    if request.method == "POST":
        name = request.POST.get('name')
        describe = request.POST.get('describe')
        phone = request.POST.get('phone')
        title = request.POST.get('title')
        new = models.Report()
        new.title = title
        new.name = name
        new.phone = phone
        new.describe = describe
        # 保存到数据库中
        new.save()
        return JsonResponse({'success': True})
    return JsonResponse({'success': False})